// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    devicesData:[],
    connectStatus:false,
    type:1,
  },
  onLoad(){
    this.initBle();
  },
  //发送动画类型到蓝牙
  sendToESP(){
    let { type } = this.data;
    if(type<5){
      type++;
      this.setData({ type });
    }
  },
  //初始化蓝牙
  initBle(){
    const _o = this;
    const { devicesData } = this.data;
    //扫描可用蓝牙设备
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(ele=>{
        if(ele.name == "ESP32_Audio"){
          // 找到设备开始连接
          _o.bleConnection(ele.deviceId);
          wx.stopBluetoothDevicesDiscovery()
        }
      })
      _o.setData({
        devicesData
      })
    });
    //初始化蓝牙模块
    wx.openBluetoothAdapter({
      mode:"central",
      success(res){
        // 开始搜寻附近的蓝牙外围设备
        wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: false,
        })
      },
      error(err){
        if(err.errCode != 10001) return;
        wx.onBluetoothAdapterStateChange((res)=>{
          if (!res.available) return
          // 开始搜寻附近的蓝牙外围设备
          wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: false,
          })
        });
      },
    });
  },
  //连接需要连接的设备
  bleConnection(devicesID){
    const _o = this;
    wx.createBLEConnection({
      devicesID, // 搜索到设备的 deviceId
      success: (res) => {
        // 连接成功，获取服务
        console.log('连接成功，获取服务',res)
        _o.setData({
          connectStatus:true,
        })
        _o.bleGetDeviceServices(devicesID)
      }
    })
  },
  bleGetDeviceServices(devicesID){
    const _o = this;
    wx.getBLEDeviceServices({
      devicesID, // 搜索到设备的 devicesID
      success: (res) => {
        console.log(res.services)
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            // 可根据具体业务需要，选择一个主服务进行通信
            _o.bleGetDeviceCharacteristics(devicesID,res.services[i].uuid)
          }
        }
      }
    })
  },
  bleGetDeviceCharacteristics(devicesID,serviceId){
    wx.getBLEDeviceCharacteristics({
      devicesID, // 搜索到设备的 devicesID
      serviceId, // 上一步中找到的某个服务
      success: (res) => {
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i];
          if (item.properties.write) { // 该特征值可写
            // 本示例是向蓝牙设备发送一个 0x00 的 16 进制数据
            // 实际使用时，应根据具体设备协议发送数据
            // let buffer = new ArrayBuffer(1)
            // let dataView = new DataView(buffer)
            // dataView.setUint8(0, 0)
            // let senddata = 'FF';
            // let buffer = this.hexString2ArrayBuffer(senddata);
            var buffer = this.stringToBytes("getid")
            this.setData({
              'deviceId':devicesID,
              'serviceId':serviceId,
              'characteristicId':item.uuid
            })
            wx.writeBLECharacteristicValue({
              devicesID,
              serviceId,
              characteristicId: item.uuid,
              value: buffer,
            })
          }
          if (item.properties.read) { // 改特征值可读
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.notify || item.properties.indicate) {
            // 必须先启用 wx.notifyBLECharacteristicValueChange 才能监听到设备 onBLECharacteristicValueChange 事件
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      }
    })
  },
  stringToBytes(str) {
    var array = new Uint8Array(str.length);
    for (var i = 0, l = str.length; i < l; i++) {
      array[i] = str.charCodeAt(i);
    }
    console.log(array);
    return array.buffer;
  },
  hextoString: function (hex) {
    var arr = hex.split("")
    var out = ""
    for (var i = 0; i < arr.length / 2; i++) {
      var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1]
      var charValue = String.fromCharCode(tmp);
      out += charValue
    }
    return out
  },
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
})
